"use client"

import { useState, useEffect } from "react"
import { useSearchParams } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { ArrowLeft, Plus, Trash2 } from "lucide-react"
import Link from "next/link"
import { mockTicketTemplates } from "@/mocks/ticket-templates"
import { TicketTemplate } from "@/types/template"
import { mockDepartments, mockUsers, mockTracks } from "@/mocks/admin-data"

interface OperationStep {
  stepNumber: number
  description: string
  device?: string
  action?: string
  isCritical?: boolean
  operatorCheck: boolean
  supervisorCheck: boolean
}

interface TicketData {
  ticketId: string
  type: string
  location: string
  department: string
  applicant: string
  operator: string
  supervisor: string
  task: {
    name: string
    target: string
    conditions: string
    requiredGear: string[]
    precautions: string[]
    startTime: string
    endTime: string
  }
}

const initialTicketData: TicketData = {
  ticketId: "",
  type: "",
  location: "",
  department: "",
  applicant: "",
  operator: "",
  supervisor: "",
  task: {
    name: "",
    target: "",
    conditions: "",
    requiredGear: [],
    precautions: [""],
    startTime: "",
    endTime: ""
  },
}

export default function CreateTicketForm() {
  const searchParams = useSearchParams()
  const [ticketData, setTicketData] = useState<TicketData>(initialTicketData)
  const [steps, setSteps] = useState<OperationStep[]>([])
  const [baseSteps, setBaseSteps] = useState<OperationStep[]>([]) // To store original template steps

  const applyTemplate = (template: TicketTemplate | undefined) => {
    if (!template) {
      setTicketData(initialTicketData)
      setSteps([])
      setBaseSteps([])
      return
    }

    const taskName = template.task.name.replace(
      "{target}",
      `(${ticketData.task.target || "待定"})`
    )
    
    // 设置默认的开始时间和结束时间
    const now = new Date()
    const startTime = now.toISOString().slice(0, 16) // 格式化为 YYYY-MM-DDTHH:MM
    
    // 默认结束时间为当前时间加4小时
    const endTime = new Date(now.getTime() + 4 * 60 * 60 * 1000).toISOString().slice(0, 16)

    setTicketData(prev => ({
      ...initialTicketData,
      type: template.type,
      location: template.location,
      department: "丁堰车辆段", // Default department
      applicant: mockUsers[2].name, // Mock default applicant
      operator: mockUsers[2].name, // Mock default operator
      supervisor: mockUsers[1].name, // Mock default supervisor
      task: {
        ...initialTicketData.task,
        name: taskName,
        conditions: template.task.conditions,
        requiredGear: [...template.task.requiredGear],
        precautions: [...template.task.precautions],
        startTime: template.task.startTime || startTime,
        endTime: template.task.endTime || endTime,
      },
    }));

    const templateSteps: OperationStep[] = template.steps.map(s => ({
      ...s,
      operatorCheck: false,
      supervisorCheck: false,
    }))

    setSteps(templateSteps)
    setBaseSteps(templateSteps)
  }

  useEffect(() => {
    const templateId = searchParams.get('templateId')
    if (templateId) {
      const template = mockTicketTemplates.find(t => t.id === templateId)
      applyTemplate(template)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams])

  useEffect(() => {
    if (baseSteps.length > 0) {
      const newSteps = baseSteps.map(step => ({
        ...step,
        description: step.description
          .replace(/\{target\}/g, ticketData.task.target || "{目标股道}")
          .replace(
            /\{adjacent_target\}/g,
            ticketData.task.target
              ? `${ticketData.task.target}相邻股道`
              : "{相邻股道}"
          ),
      }))
      setSteps(newSteps)

      const template = mockTicketTemplates.find(t => t.type === ticketData.type)
      if (template) {
        const taskName = template.task.name.replace(
          "{target}",
          ticketData.task.target || "{目标股ado}"
        )
        setTicketData(prev => ({
          ...prev,
          task: { ...prev.task, name: taskName },
        }))
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ticketData.task.target, baseSteps])

  const handleTypeChange = (selectedType: string) => {
    const template = mockTicketTemplates.find(t => t.type === selectedType)
    applyTemplate(template)
  }

  const createTicket = () => {
    if (!ticketData.task.name || steps.length === 0) {
      alert("请选择一个典型票模板并填写所有必填项。")
      return
    }
    // Logic to create the ticket
    console.log("Creating ticket with data:", { ticketData, steps })
    alert("作业票已成功创建！")
    // TODO: Redirect to the ticket list or the new ticket's detail page
  }

  const updateTicketData = (field: string, value: string) => {
    const fields = field.split(".")
    if (fields.length === 1) {
      setTicketData({ ...ticketData, [field]: value })
    } else if (fields.length === 2 && fields[0] === "task") {
      const updatedTask = { ...ticketData.task, [fields[1]]: value }
      setTicketData({ ...ticketData, task: updatedTask })
    }
  }

  const handlePersonnelChange = (field: string, value: string) => {
    setTicketData({ ...ticketData, [field]: value })
  }

  const handleDepartmentChange = (value: string) => {
    setTicketData({ ...ticketData, department: value })
  }

  const updatePrecaution = (index: number, value: string) => {
    const updatedPrecautions = [...ticketData.task.precautions]
    updatedPrecautions[index] = value
    setTicketData({ ...ticketData, task: { ...ticketData.task, precautions: updatedPrecautions } })
  }

  const removePrecaution = (index: number) => {
    setTicketData({
      ...ticketData,
      task: { ...ticketData.task, precautions: ticketData.task.precautions.filter((_, i) => i !== index) }
    })
  }
  
  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white shadow-sm border-b sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center space-x-4">
              <Link href="/tickets">
                <Button variant="outline">
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  返回列表
                </Button>
              </Link>
              <h1 className="text-xl font-semibold text-gray-900 border-l pl-4">新建操作票</h1>
            </div>
            <div className="flex items-center space-x-2">
              <Button onClick={createTicket}>
                <Plus className="mr-2 h-4 w-4" />
                创建作业票
              </Button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
          <div className="col-span-1 space-y-6 lg:col-span-2">
            {/* 基本信息 */}
            <Card>
              <CardHeader>
                <CardTitle>基本信息</CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="ticket-type">选择典型票</Label>
                  <Select
                    onValueChange={handleTypeChange}
                    value={ticketData.type}
                  >
                    <SelectTrigger id="ticket-type">
                      <SelectValue placeholder="请选择一个典型票模板" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockTicketTemplates.map(template => (
                        <SelectItem key={template.id} value={template.type}>
                          {template.type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="location">作业地点</Label>
                  <Input
                    id="location"
                    value={ticketData.location}
                    onChange={e => updateTicketData("location", e.target.value)}
                    placeholder="例如：丁堰车辆段"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="department">作业部门</Label>
                  <Select
                    onValueChange={handleDepartmentChange}
                    value={ticketData.department}
                  >
                    <SelectTrigger id="department">
                      <SelectValue placeholder="选择部门" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockDepartments.map(dept => (
                        <SelectItem key={dept.id} value={dept.name}>
                          {dept.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="applicant">申请人</Label>
                   <Select
                    onValueChange={(value) => handlePersonnelChange('applicant', value)}
                    value={ticketData.applicant}
                  >
                    <SelectTrigger id="applicant">
                      <SelectValue placeholder="选择申请人" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockUsers.map(user => (
                        <SelectItem key={user.id} value={user.name}>
                          {user.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="operator">操作人</Label>
                   <Select
                    onValueChange={(value) => handlePersonnelChange('operator', value)}
                    value={ticketData.operator}
                  >
                    <SelectTrigger id="operator">
                      <SelectValue placeholder="选择操作人" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockUsers.map(user => (
                        <SelectItem key={user.id} value={user.name}>
                          {user.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="supervisor">监护人</Label>
                   <Select
                    onValueChange={(value) => handlePersonnelChange('supervisor', value)}
                    value={ticketData.supervisor}
                  >
                    <SelectTrigger id="supervisor">
                      <SelectValue placeholder="选择监护人" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockUsers.map(user => (
                        <SelectItem key={user.id} value={user.name}>
                          {user.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>

            {/* 任务信息 */}
            <Card>
              <CardHeader>
                <CardTitle>任务信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="task-name">任务名称</Label>
                  <Input
                    id="task-name"
                    value={ticketData.task.name}
                    readOnly
                    className="bg-gray-50"
                    placeholder="例如：11G接触网隔离开关送电操作"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="task-target">作业目标</Label>
                   <Select
                    onValueChange={(value) => updateTicketData("task.target", value)}
                    value={ticketData.task.target}
                    disabled={ticketData.type ? false : true}
                  >
                    <SelectTrigger id="task-target">
                      <SelectValue placeholder="选择作业目标股道" />
                    </SelectTrigger>
                    <SelectContent>
                      {mockTracks.map(track => (
                        <SelectItem key={track.id} value={track.name}>
                          {track.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="task-start-time">开始时间</Label>
                    <Input
                      id="task-start-time"
                      type="datetime-local"
                      value={ticketData.task.startTime}
                      onChange={e => updateTicketData("task.startTime", e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="task-end-time">结束时间</Label>
                    <Input
                      id="task-end-time"
                      type="datetime-local"
                      value={ticketData.task.endTime}
                      onChange={e => updateTicketData("task.endTime", e.target.value)}
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="task-conditions">作业条件</Label>
                  <Textarea
                    id="task-conditions"
                    value={ticketData.task.conditions}
                    readOnly
                    className="bg-gray-50"
                    placeholder="例如：确认相关作业已结束..."
                    rows={2}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label>安全注意事项</Label>
                  <div className="space-y-3">
                    {ticketData.task.precautions.map((precaution, index) => (
                      <div key={index} className="flex items-start space-x-2">
                        <Textarea
                          value={precaution}
                          readOnly
                          className="flex-1 bg-gray-50"
                          placeholder="例如：确认相关作业已结束..."
                        />
                      </div>
                    ))}
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 操作步骤 */}
            <Card>
              <CardHeader>
                <CardTitle>操作步骤</CardTitle>
              </CardHeader>
              <CardContent>
                {steps.length > 0 ? (
                  <div className="space-y-4">
                    {steps.map(step => (
                      <div
                        key={step.stepNumber}
                        className="flex items-start space-x-4 rounded-md border p-4"
                      >
                        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground">
                          {step.stepNumber}
                        </div>
                        <div className="flex-1 space-y-1">
                          <p className="font-medium">{step.description}</p>
                          <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
                            {step.device && <span>设备: {step.device}</span>}
                            {step.action && <span>操作: {step.action}</span>}
                            {step.isCritical && (
                              <span className="font-semibold text-destructive">
                                关键步骤
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center text-muted-foreground">
                    请先从上方选择一个典型票模板来加载操作步骤。
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <div className="col-span-1 space-y-6 lg:col-span-1">
            {/* 右侧内容 */}
          </div>
        </div>
      </main>
    </div>
  )
} 